<template>
    <div class="course">
        <div class="navi">
            <!-- <div class="navi-date" @click="openDatePicker" :class="{active : isDateVisible}">
                <div class="rili" :style="{color: isDateVisible ? 'red' : 'inherit'}">
                    <div class="rili-text">
                        <img :src="isDateVisible ? dateSelected : dateDefault "/>
                        日历
                        <img :src="isDateVisible ? downSelected : downDefault" />
                    </div>
                    <div>
                        <el-date-picker
                        v-model="selectedDate"
                        matchtype="date"
                        @change="handleDateChange"
                        :disabled-date="disabledDate"
                        ref="datePicker"
                        :visible="isDatePickerVisible"
                        class="hidden-datepicker"
                        />
                    </div>
                </div>
            </div> -->
            <div class="text" v-for="(item, index) in visibleNaviItems" :key="index"
                :class="{ active: activeIndex === item.date }" @click="handleItemClick(item)">
                <span class="text-span">{{ item.date }} </span>
                <span style="font-size: 12px;">{{ item.week }}</span>
            </div>
        </div>
        <div class="table">
            <MatchTable v-if="tableData" v-loading="tableloading" :data="tableData" :current-page="currentPage" :page-size="pageSize"
                :total="totalItems" @update:currentPage="onPageChange" @update:pageSize="onPageSizeChange"
                :height="height" :matchtype="matchtype"/>
        </div>
    </div>
</template>
<script setup>
import downSelected from '@/assets/table/down-selected.png'
import downDefault from '@/assets/table/down-default.png'
import dateSelected from '@/assets/table/date-selected.png'
import dateDefault from '@/assets/table/date-default.png'
import MatchTable from './MatchTable.vue';


import { minfoListEarly } from "@/api/match.js";

const props = defineProps({
  matchtype: String
});
const naviItem = ref([])


const tableData = ref([])
const loading = ref(false); // 加载状态
const hasMorePages = ref(true); // 是否有更多页面
const currentPage = ref(1); // 当前页
const pageSize = ref(20); // 每页条目数
const totalItems = ref(0); // 总条数
const height = 'calc(100vh - 220px)'
// 使用 IntersectionObserver 监听加载更多的触发点
const loadMoreTrigger = ref(null);

const selectedDate = ref(null);
const isDatePickerVisible = ref(false);
const isDateVisible = ref(false); // 控制图片的颜色

const activeIndex = ref('')
const tableloading = ref(false)
const visibleNaviItems = computed(() => {
    const weekdays = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    let today = new Date();  // 获取当前日期
    let result = [];

    for (let i = 0; i < 7; i++) {
        let nextDay = new Date(today);
        nextDay.setDate(today.getDate() + i);  // 设置日期为今天 + i 天

        // 格式化为 "年-月-日"
        let year = nextDay.getFullYear();
        let month = String(nextDay.getMonth() + 1).padStart(2, '0');  // 月份从0开始，需要加1
        let day = String(nextDay.getDate()).padStart(2, '0');  // 日期需要补零
        let weekday = weekdays[nextDay.getDay()];  // 获取中文星期几

        // result.push(`${year}-${month}-${day} (${weekday})`);

        result.push({
            date: `${year}-${month}-${day}`,
            week: weekday
        })
    }

    
    return result
});


const handleItemClick = async (item) => {
    activeIndex.value = item.date; // 更新选中的索引
    currentPage.value = 1; // 重置页码
    hasMorePages.value = true; // 重置是否有更多页面
    tableData.value = []; // 清空之前的数据 1500  6000  4000

    const body = {
        date: item, // 传入选中的日期
        lids: [],
        page: currentPage.value
    };

    try {
        // 先加载第一页数据
        await fetchPageData(body);

        // 在第一页数据加载完成后，开始监听触发点
    } catch (error) {
        console.error("获取数据时发生错误:", error);
    }
};

const fetchPageData = async () => {
    if (loading.value) return; // 避免重复请求
    loading.value = true;
    tableloading.value = true
    const body = {
        // naviItem.value[activeIndex.value]
        date: activeIndex.value,
        // lids: [],
        page: currentPage.value,
        page_size: 20
    };

    try {
        const res = await minfoListEarly(body);
        totalItems.value = res.total; // 更新总条数
        const totalList = res.list; // 当前请求的数据
        let allData = [...totalList]; // 初始化合并数据的数组
        tableloading.value = false


        tableData.value = allData; // 更新最终的数据
    } catch (error) {
        tableData.value = []
        tableloading.value = false
    } finally {
        // tableData.value = []
        loading.value = false;
        tableloading.value = false
    }
};

const onPageChange = async (newPage) => {
    if (pageSize.value / 20 === 2) {
        currentPage.value = 2 * newPage - 1;
    } else if (pageSize.value / 20 === 3) {
        currentPage.value = 3 * newPage - 2
    } else {
        currentPage.value = newPage
    }
    await fetchPageData();
};

const onPageSizeChange = async (newSize) => {
    pageSize.value = newSize; // 更新每页条数
    currentPage.value = 1; // 重置为第一页
    await fetchPageData(); // 重新请求第一页数据
};
onMounted(() => {
    if (activeIndex.value == '') {
        activeIndex.value = visibleNaviItems.value[0].date
    }
    fetchPageData()
})

</script>
<style lang='scss' scoped>
.navi {
    display: flex;
    height: 44px;
    cursor: pointer;
    background-color: #ebebeb;
    position: relative;
    padding: 0 2px;
}

.navi-date {
    display: flex;
    position: relative;
}

.rili {
    width: 100px;
    position: relative;

}

.rili-text {
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    margin-top: 10px;
    margin-left: 20px;
}

.text {
    display: flex;
    justify-content: center;
    align-items: center;
    text-align: center;
    flex-direction: column;
    font-size: 14px;
    z-index: 999;
}

.text-span {
    width: 182px;
}

.text.active {
    background-color: #fff; // 选中时背景颜色
    color: #e92937; // 选中时字体颜色
    font-weight: 600;
    margin: 2px 0;
}

.loading-indicator {
    text-align: center;
    padding: 16px;
}

.load-more-trigger {
    height: 1px;
}

/* 隐藏 DatePicker 的输入框和边框 */
:deep(.hidden-datepicker .el-input__wrapper) {
    display: none;
    /* 隐藏输入框 */
}

.hidden-datepicker .el-input {
    border: none;
    /* 隐藏边框 */
    padding: 0;
    /* 清除默认 padding */
}
</style>